<template>
  <div>
    <el-tabs v-model="activeName">
      <el-tab-pane
        v-for="(item, index) in targets"
        :key="index"
        :label="item.name"
        :name="index.toString()"
      >
      </el-tab-pane>
    </el-tabs>
    <!-- 雨量 -->
    <div class="content" v-if="activeName === '0'">
      <div class="data">
        <el-table
          :data="filteredData"
          stripe
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
          :row-style="rowStyle"
        >
          <el-table-column
            prop="serialNumber"
            label="序号"
            width="73"
          ></el-table-column>
          <el-table-column
            prop="hiddenPointName"
            label="名称"
            width="150"
          ></el-table-column>
          <el-table-column
            prop="disasterId"
            label="景区ID"
            width="200"
          ></el-table-column>
          <el-table-column prop="type" label="景区级别"></el-table-column>
          <el-table-column prop="district" label="区县"></el-table-column>
          <el-table-column prop="township" label="乡镇"></el-table-column>
          <el-table-column
            prop="village"
            label="村"
            width="70"
          ></el-table-column>
          <el-table-column
            prop="nearestWeatherStation"
            label="最近气象站"
          ></el-table-column>
          <el-table-column prop="distance" label="距离"></el-table-column>
          <el-table-column
            prop="oneHourRainfall"
            label="1小时雨量"
          ></el-table-column>
          <el-table-column
            prop="twoHourRainfall"
            label="2小时雨量"
          ></el-table-column>
          <el-table-column
            prop="threeHourRainfall"
            label="3小时雨量"
          ></el-table-column>
          <el-table-column
            prop="sixHourRainfall"
            label="6小时雨量"
          ></el-table-column>
          <el-table-column
            prop="minuteRainfall"
            label="每分钟雨量"
          ></el-table-column>
          <el-table-column
            prop="oneHourForecast"
            label="1h雨量预报"
          ></el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 雨量预警 -->
    <div class="select" v-if="activeName === '1'">
      <!-- 开始日期 -->
      <el-date-picker
        v-model="beginTime"
        type="datetime"
        placeholder="请选择开始日期"
      >
      </el-date-picker>
      <!-- 结束日期 -->
      <el-date-picker
        v-model="endTime"
        type="datetime"
        placeholder="请选择结束日期"
        style="margin: 0 20px"
      >
      </el-date-picker>
      <!-- 区县 -->
      <el-select
        placeholder="县(区)"
        v-model="area"
        @change="areaChange"
        style="margin-right: 20px"
      >
        <el-option
          v-for="item in areaOptions"
          :key="item.value"
          :label="item.value"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <button @click="getWarn(formattedBeginTime, formattedEndTime)">
        查询
      </button>
    </div>
    <div class="content" v-if="activeName === '1'">
      <div class="data">
        <el-table
          :data="tableData2"
          stripe
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
          :row-style="rowStyle"
          height="70vh"
        >
          <el-table-column
            prop="serialNumber"
            label="序号"
            width="73"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="名字"
          ></el-table-column>
          <el-table-column prop="sendTime" label="时间"></el-table-column>
          <el-table-column prop="type" label="类型"></el-table-column>
          <el-table-column prop="county" label="区县"></el-table-column>
          <el-table-column prop="town" label="乡镇"></el-table-column>
          <el-table-column prop="village" label="村"></el-table-column>
          <el-table-column prop="sgroup" label="隐患点"></el-table-column>
          <el-table-column prop="tel" label="电话" width="100"></el-table-column>
          <el-table-column prop="content" label="内容" width="600"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>  
  
<script>
import axios from "axios";
export default {
  data() {
    return {
      activeName: 0,
      targets: [{ name: "文旅场所雨量" }, { name: "文旅场所雨量预警" }],
      county: localStorage.getItem("county"),
      loading: true,
      forecastTime: "",
      currentTime: "",
      selectedDistrict: "all-types",
      selectedTownship: "all-townships",
      selectedPrecipitation: "all-types",
      tableData: [],
      currentPage: 1,
      pageSize: 9999,
      totalRecords: 0,
      uniqueDistricts: [],
      uniqueTownships: [],
      uniqueTypes: [],
      dialogVisible: false,
      selectedRow: null,
      contacts: [],
      disasterId: "",
      tableData2: [],
      beginTime: null,
      endTime: null,
       // 地区
       area: "雅安",
      // 地区选择器
      areaOptions: [
        {
          value: "雅安",
        },
        {
          value: "雨城",
        },
        {
          value: "经开",
        },
        {
          value: "名山",
        },
        {
          value: "天全",
        },
        {
          value: "芦山",
        },
        {
          value: "宝兴",
        },
        {
          value: "荥经",
        },
        {
          value: "汉源",
        },
        {
          value: "石棉",
        },
      ],
    };
  },
  computed: {
    filteredData() {
      return this.tableData.filter((item) => {
        return (
          (this.selectedDistrict === "all-types" ||
            item.district === this.selectedDistrict) &&
          (this.selectedTownship === "all-townships" ||
            item.township === this.selectedTownship) &&
          (this.selectedPrecipitation === "all-types" ||
            item.type === this.selectedPrecipitation) &&
          item.type !== "山洪沟"
        );
      });
    },
    formattedBeginTime() {
      return this.beginTime.toISOString().split(".")[0].replace("T", " ");
    },
    formattedEndTime() {
      return this.endTime.toISOString().split(".")[0].replace("T", " ");
    },
  },
  methods: {
    headerCellStyle() {
      return {
        background: "#011A10",
        color: "#fff",
        opacity: 0.8,
      };
    },
    cellStyle() {
      return {
        background: "#00371D",
        color: "#fff",
      };
    },
    rowStyle() {
      return {
        height: "30px",
      };
    },
    // 雨量
    fetchData(type) {
      const token =
        "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImM5ZGQ0NGEwLTJhM2YtNDQ2NS1hMDExLTc5MDMxOWYyNGFiMiJ9.N4Vo7_C4bgcMMlsiSjW-WxV2MwF35cjc4PY9Bzo1fdHBRENkBc1gEK2_-spdACkQl9KMgxJ81KmbuS9vzdwBBw";
      const config = {
        headers: {
          token: token,
        },
        params: {
          pageNum: 1,
          pageSize: 9999,
          isTravel: true,
          type: type,
        },
      };
      axios
        .get(
          "http://4fb22b9f.r1.cpolar.top/yaqxfw/precisetarget/listOfRainOfGeology",
          config
        )
        .then((response) => {
          if (response.status === 200 && response.data.code === 200) {
            //console.log(response);

            const records = response.data.data.records;
            this.tableData = records
              .filter((record) => record.type !== "山洪沟")
              .map((record, index) => ({
                serialNumber:
                  (this.currentPage - 1) * this.pageSize + index + 1,
                hiddenPointName: record.dsname,
                type: record.type,
                district: record.county,
                township: record.town,
                village: record.village,
                nearestWeatherStation: record.meteorologicalStation,
                distance: record.distance,
                oneHourRainfall: record.rain1h,
                twoHourRainfall: record.rain2h,
                threeHourRainfall: record.rain3h,
                sixHourRainfall: record.rain6h,
                minuteRainfall: record.rainMinute,
                oneHourForecast: record.rain1hYb,
                disasterId: record.disasterId,
              }));
            this.totalRecords = response.data.data.total;
            this.extractUniqueDistricts(records);
            this.extractUniqueTypes(records);
            this.updateUniqueTownships();
          } else {
            this.$message.error(`Error: ${response.data.msg}`);
          }
          this.loading = false;
        })
        .catch((error) => {
          this.$message.error(`Request failed: ${error}`);
          this.loading = false;
        });
    },
    extractUniqueDistricts(records) {
      const districts = records.map((record) => record.county);
      this.uniqueDistricts = [...new Set(districts)];
    },
    extractUniqueTypes(records) {
      const types = records
        .map((record) => record.type)
        .filter((type) => type !== "山洪沟");
      this.uniqueTypes = [...new Set(types)];
    },
    updateUniqueTownships() {
      if (this.selectedDistrict === "all-types") {
        this.uniqueTownships = [];
        return;
      }
      const townships = this.tableData
        .filter((record) => record.district === this.selectedDistrict)
        .map((record) => record.township);
      this.uniqueTownships = [...new Set(townships)];
    },
    beginDefault() {
      const now = new Date();
      const sevenDaysAgo = new Date(now);
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      sevenDaysAgo.setHours(0, 0, 0, 0);
      return sevenDaysAgo.toISOString().split(".")[0].replace("T", " ");
    },
    // 计算结束时间（今天的23:59:59.999）
    endDefault() {
      const now = new Date();
      const endOfDay = new Date(now);
      endOfDay.setHours(23, 59, 59, 999);
      return endOfDay.toISOString().split(".")[0].replace("T", " ");
    },
    //雨量预警
    getWarn(beginTime, endTime) {
      const token1 =
        "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImM5ZGQ0NGEwLTJhM2YtNDQ2NS1hMDExLTc5MDMxOWYyNGFiMiJ9.N4Vo7_C4bgcMMlsiSjW-WxV2MwF35cjc4PY9Bzo1fdHBRENkBc1gEK2_-spdACkQl9KMgxJ81KmbuS9vzdwBBw";
      const config2 = {
        headers: {
          token: token1,
        },
      };
      axios
        .post(
          "http://4fb22b9f.r1.cpolar.top/yaqxfw/precisetarget/rainfallWarningStatistics",
          {
            pageQuery: {
              pageSize: 999,
              pageNum: 1,
            },
            begin: beginTime ? beginTime : this.beginDefault,
            end: endTime ? endTime : this.endDefault,
            diseaterClass:'地质灾害'
          },
          config2
        )
        .then((res) => {
          const records2 = res.data.data.records;
          this.tableData2 = records2
            .filter((record) => record.type !== "山洪沟")
            .map((record, index) => ({
              serialNumber: (this.currentPage - 1) * this.pageSize + index + 1,
              content: record.content,
              county: record.county,
              name: record.name,
              sendTime: record.sendTime,
              sgroup: record.sgroup,
              tel: record.tel,
              town: record.town,
              type: record.type,
              village: record.village,
            }));
        });
    },
  },
  mounted() {
    this.fetchData("地质灾害");
  },
  created() {  
    this.beginTime = new Date(this.beginDefault());  
    this.endTime = new Date(this.endDefault());  
  }, 
  watch: {  
    // 监听activeName的变化  
    activeName(newVal) {   
      if (newVal === '0') {  
        this.fetchData("地质灾害");  
      } else if (newVal === '1') {  
        this.getWarn(this.formattedBeginTime, this.formattedEndTime);  
      }  
    }  
  },  
};
</script>  
  
<style scoped lang="scss">

.select {
    width: 100%;
    height: 5%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin: 20px 0;
    button {
      width: 100px;
      height: 40px;
      background: none;
      border: #47c364 1px solid;
      border-radius: 5px;
      color: #fff;
    }
  }
</style>